package com.oig.common.module;

import cn.hutool.core.util.StrUtil;
import com.oig.common.constants.CommonEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@Data
@Schema(description = "查询参数对象")
public class SysRequest<T> {

    @Schema(description = "第几页,从1开始")
    private Integer pageNo ;
    @Schema(description = "每页几条数据")
    private Integer pageSize;
    @Schema(description = "查询条件")
    private T paramDto;

    @Schema(description = "排序字段,单个属性名称")
    private String sortColumn;
    @Schema(description = "排序类型,枚举 DESC , ASC，如果sortColumn填了，sort不填默认asc")
    private String sort;

    /**
     * 默认查第一页，10行
     */
    public SysRequest(){
        this.pageNo=1;
        this.pageSize=10;
    }

    public SysRequest(Integer pageNo, Integer pageSize){
        this.pageNo=pageNo;
        this.pageSize=pageSize;
    }

    public SysRequest(T paramDto){
        this.pageNo=1;
        this.pageSize=10;
        this.paramDto=paramDto;
    }


    public SysRequest(Integer pageNo, Integer pageSize, T paramDto){
        this.pageNo=pageNo;
        this.pageSize=pageSize;
        this.paramDto=paramDto;
    }


    public Pageable pageable(){
        if (StrUtil.isNotBlank(sortColumn)) {
            Sort pageSort;
            if (CommonEnum.SortEnum.DESC.getCode().equals(sort.toUpperCase())) {
                pageSort = Sort.by(Sort.Direction.DESC, sortColumn);
            } else {
                pageSort = Sort.by(Sort.Direction.ASC, sortColumn);
            }
            //PageRequest.of page是从0开始的
            return PageRequest.of(pageNo>0?pageNo-1:0, pageSize, pageSort);
        } else {
            return PageRequest.of(pageNo>0?pageNo-1:0, pageSize);
        }
    }

}
